package com.platform.qujia.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.dao.PresentCouponUserRecordMapper;
import com.platform.qujia.enums.CardRecordType;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.CancelCouponDto;
import com.platform.qujia.pojo.dto.CouponPaymetDto;
import com.platform.qujia.pojo.vo.CouponInfoVO;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.CryptUtil;
import com.platform.qujia.utils.IdempotentUtil;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * <Title> CouponController </Title>
 * <Description> 无力吐槽的优惠券设计，无力吐槽的表结构设计</Description>
 *
 * @Date 2021年12月3日
 */

@RestController
@Api(tags = "优惠券")
@CrossOrigin
@Slf4j
public class CouponController {
    private static Logger logger = (Logger) LoggerFactory.getLogger(PosMachineController.class);
    @Resource
    private CouponService couponService;
    @Resource
    private GradeService gradeService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private PosMachineService posMachineService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private EnterpriseService enterpriseService;
    @Autowired
    private IdempotentUtil idempotentUtil;
    @Resource
    private WxPushUtil wxPushUtil;
    @Value("${qujia.domainName}")
    private String domainName;

    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;

    @Resource
    private CouponWriteOffRecordsService couponWriteOffRecordsService;

    @Resource
    private RegistrationReleaseService registrationReleaseService;

    @Resource
    private PresentCouponUserRecordMapper presentCouponUserRecordMapper;


    /*
     * 领取方式查询优惠券
     * @return
     */
    @ApiOperation(value = "领取方式查询优惠券", httpMethod = "GET")
    @GetMapping("/selectCouponListByCouponIssueId")
    public String selectCouponListByCouponIssueId(@RequestParam String couponIssueId, String ordNo, String mobilePhone) {
        log.info("领取方式ID：" + couponIssueId);
        ResultData resultData = null;
        String randomFlag = System.currentTimeMillis() + RandomStringUtils.randomNumeric(7);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        if (StringUtils.isNotBlank(couponIssueId)) {
            Map<String, Object> activity = couponService.getActivityAllByActivityId(couponIssueId);
            //                        对限制的会员做判断
            if(activity.get("member_condition")!=null&&activity.get("member_condition").toString().equals("part")&&activity.get("member_level")!=null&&activity.get("enterprise_id")!=null){
                Long enterpriseId = (Long)activity.get("enterprise_id");
                String   userMemberLevel = couponService.getAppUserGrowLevel(mobilePhone,enterpriseId);
                String memberLevel = activity.get("member_level").toString();
                if (memberLevel.contains(userMemberLevel)) {
                    // userMemberLevel在memberLevel中包含
                    // 做相应的处理...
                } else {
                    return gson.toJson(ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL));
                }
            }
            if (!activity.isEmpty()) {
                if (activity.get("is_deleted").toString().equals("true")) {
                    return gson.toJson(ResultData.error(new CodeMsg(-21, "活动已删除")));
                }
                if (!activity.get("activity_status").equals("1")) {
                    return gson.toJson(ResultData.error(new CodeMsg(-21, "活动未生效或已失效")));
                }
                // 获取当前时间
                Date currentTime = new Date();

                // 定义时间格式
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 获取活动的开始时间和结束时间字符串
                String startTimeString = activity.get("activity_start_time").toString();
                String endTimeString = activity.get("activity_end_time").toString();

                try {
                    // 将字符串解析为Date对象
                    Date startTime = dateFormat.parse(startTimeString);
                    Date endTime = dateFormat.parse(endTimeString);

                    // 比较当前时间与开始时间、结束时间
                    if (currentTime.after(startTime) && currentTime.before(endTime)) {
                        System.out.println("当前时间在活动时间范围内");
                    } else if (currentTime.before(startTime)) {
                        return gson.toJson(ResultData.error(new CodeMsg(-21, "当前时间在活动开始时间之前")));
                    } else {
                        return gson.toJson(ResultData.error(new CodeMsg(-21, "当前时间在活动结束时间之后")));

                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            List<String> couponIssueIds = couponService.getIssueIdsandCouponByActivityId(couponIssueId);
//            List<CouponIssue> couponIssues = new ArrayList<>();
//
//            for (String issueId : couponIssueIds) {
//                Map<String, Object> params = new HashMap<>();
//                params.put("couponIssueId", issueId);
//                List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
//
//
//                if (selectedCouponIssues != null && !selectedCouponIssues.isEmpty()) {
//                    CouponIssue firstCouponIssue = selectedCouponIssues.get(0);
//                    firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("1");
//                    int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(issueId).build());
//                    CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(issueId).randomFlag(randomFlag).build());
//
//                    if (firstCouponIssue != null && userIssueGiveCount >= firstCouponIssue.getGiveCount()) {
//                        firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
//                    }
//                    if (cugc != null && cugc.getIssueGiveCount() + 1 >= firstCouponIssue.getGiveLimit()) {
//                        firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
//                    } else if (1 >= firstCouponIssue.getGiveLimit()) {
//                        firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
//                    }
//                    if (firstCouponIssue != null) {
//                        List<Station> stationList = firstCouponIssue.getStaList();
//                        if (stationList != null && !stationList.isEmpty()) {
//                            List<String> stationNames = stationList
//                                    .stream()
//                                    .map(Station::getStationName)
//                                    .filter(Objects::nonNull) // 过滤掉空值
//                                    .collect(Collectors.toList());
//                            if (!stationNames.isEmpty()) {
//                                String concatenatedNames = String.join(";", stationNames);
//                                firstCouponIssue.getCouponTemplateList().get(0).setCouponStaNames(concatenatedNames);
//                            }
//                        }
//                    }
//                }
//                couponIssues.addAll(selectedCouponIssues);
//            }
            List<CouponIssue> couponIssues = new ArrayList<>();
            List<Callable<List<CouponIssue>>> callables = new ArrayList<>();

            for (String issueId : couponIssueIds) {
                Callable<List<CouponIssue>> callable = () -> {
                    Map<String, Object> params = new HashMap<>();
                    params.put("couponIssueId", issueId);
                    List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);

                    if (selectedCouponIssues != null && !selectedCouponIssues.isEmpty()) {
                        CouponIssue firstCouponIssue = selectedCouponIssues.get(0);
                        firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("1");
                        int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(issueId).build());
                        CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(issueId).randomFlag(randomFlag).build());

                        if (firstCouponIssue != null && userIssueGiveCount >= firstCouponIssue.getGiveCount()) {
                            firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
                        }
                        if (cugc != null && cugc.getIssueGiveCount() + 1 >= firstCouponIssue.getGiveLimit()) {
                            firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
                        } else if (1 >= firstCouponIssue.getGiveLimit()) {
                            firstCouponIssue.getCouponTemplateList().get(0).setAbleFlag("0");
                        }
                        if (firstCouponIssue != null) {
                            List<Station> stationList = firstCouponIssue.getStaList();
                            if (stationList != null && !stationList.isEmpty()) {
                                List<String> stationNames = stationList
                                        .stream()
                                        .map(Station::getStationName)
                                        .filter(Objects::nonNull) // 过滤掉空值
                                        .collect(Collectors.toList());
                                if (!stationNames.isEmpty()) {
                                    String concatenatedNames = String.join(";", stationNames);
                                    firstCouponIssue.getCouponTemplateList().get(0).setCouponStaNames(concatenatedNames);
                                }
                            }
                        }
                    }
                    return selectedCouponIssues;
                };
                callables.add(callable);
            }

            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            try {
                List<Future<List<CouponIssue>>> futures = executorService.invokeAll(callables);
                for (Future<List<CouponIssue>> future : futures) {
                    couponIssues.addAll(future.get());
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            } finally {
                executorService.shutdown();
            }
            if (null != couponIssues && couponIssues.size() >= 1) {
                for (CouponIssue cc : couponIssues) {
                    if (cc.getCouponTemplateList() != null && cc.getCouponTemplateList().size() >= 1) {
                        for (CouponTemplate c : cc.getCouponTemplateList()) {
                            BigDecimal aa = couponService.queryMinUseCouponAtmByCouponTemlete(c.getCouponTemplateId());
                            c.setMinUseCouponAmt(aa);
                        }
                    }
                }

                // 根据阈值金额进行排序，降序排列
                List<CouponIssue> collect = couponIssues.stream().sorted(Comparator.comparing(CouponIssue::getCouponThresholdAmt).reversed()).collect(Collectors.toList());
                CouponIssue couponIssue = collect.get(0);
                couponIssue.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
                List<CouponTemplate> updatedTemplates = new ArrayList<>();

                for (CouponIssue couponIssueItem : collect) {
                    updatedTemplates.addAll(couponIssueItem.getCouponTemplateList());
                }
                couponIssue.setCouponTemplateList(updatedTemplates);
                resultData = ResultData.success(couponIssue);
            } else {
                resultData = ResultData.error(CodeMsg.NO_COUPON);
            }
        } else {
            resultData = ResultData.error(CodeMsg.NO_ISSUE);
        }
        return gson.toJson(resultData);
    }

    private List<CouponTemplate> changeDrawCouponStatus(List<CouponTemplate> couTemList, String str) {
        List<CouponTemplate> resultList = new ArrayList<>();
        for (CouponTemplate c : couTemList) {
            c.setCouDrawStatus(str);
            resultList.add(c);
        }
        return couTemList;
    }

    /**
     * 优惠券业务逻辑说明：（牛掰的优惠券设计与表结构！！！后来者如有能力重写或重设计此部分业务逻辑吧。。。其他地方也会有臃肿的代码，如有能力能改业务设计就改吧。。）
     * 用户领取优惠券时 会携带随机数 randomFlag；根据传来随机数是否一样来判断是否是同一次进入领取优惠券页面；
     * couDrawStatus：标识用户领取优惠券状态，用于前端展示;(用户一次进来分多次领取)
     * 用户领取优惠券
     *
     * @param drawCoupon
     * @return
     */
    @Transactional
    @ApiOperation(value = "用户领取优惠券", httpMethod = "POST")
    @PostMapping("/drawCoupons")
    public String drawCoupons(@RequestBody DrawCoupon drawCoupon) {
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        log.info("领取活动ID：" + drawCoupon.getCouponIssueId() + "; 手机号：" + drawCoupon.getMobilePhone() + "; 优惠券IDs：" + drawCoupon.getCouTemIds() + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        String couponActivityId  =  drawCoupon.getCouponIssueId();

        if (StringUtils.isNotBlank(drawCoupon.getCouponIssueId()) && StringUtils.isNotBlank(drawCoupon.getCouTemIds()) && StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
            List<String> couponIssueIds = new ArrayList<>();
            Map<String, Object> couponIssueIdsMap = couponService.getActivityAllByActivityId(drawCoupon.getCouponIssueId());
            if(couponIssueIdsMap == null || couponIssueIdsMap.get("enterprise_id") == null){
                return gson.toJson(ResultData.error(CodeMsg.NO_COUPON_ISSUE));
            }
            if(couponIssueIdsMap.get("user_ment_list") != null &&  couponIssueIdsMap.get("user_ment_list").toString().contains("1")){
                String isLabelUser  = couponService.checkisLabelUser(drawCoupon.getMobilePhone(),(Long)couponIssueIdsMap.get("enterprise_id"),drawCoupon.getCouponIssueId());
                if(isLabelUser.equals("0")){
                    return gson.toJson(ResultData.error(CodeMsg.COUPON_NEW_USER));
                }
            }
            couponIssueIds = couponService.getIssueIdsByActivityId(drawCoupon.getCouponIssueId());
            //                        对限制的会员做判断
            if(couponIssueIdsMap.get("member_condition")!=null&&couponIssueIdsMap.get("member_condition").toString().equals("part")&&couponIssueIdsMap.get("member_level")!=null&&couponIssueIdsMap.get("enterprise_id")!=null){
                Long enterpriseId = (Long)couponIssueIdsMap.get("enterprise_id");
                String   userMemberLevel = couponService.getAppUserGrowLevel(drawCoupon.getMobilePhone(),enterpriseId);
                String memberLevel = couponIssueIdsMap.get("member_level").toString();
                if (memberLevel.contains(userMemberLevel)) {
                    // userMemberLevel在memberLevel中包含
                    // 做相应的处理...
                } else {
                    return gson.toJson(ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL));
                }
            }
            List<CouponIssue> couponIssueAll = new ArrayList<>();
            Iterator<String> iterator = couponIssueIds.iterator();
            List<CouponTemplate> couponInfoList = new ArrayList<>();
            while (iterator.hasNext()) {
                String issueId = iterator.next();
                Map<String, Object> params = new HashMap<>();
                params.put("couponIssueId", issueId);
                List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
                int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(issueId).build());
                CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(issueId).randomFlag(drawCoupon.getRandomFlag()).build());
                if (!selectedCouponIssues.isEmpty() && userIssueGiveCount >= selectedCouponIssues.get(0).getGiveCount()) {
                    iterator.remove();
                    continue;
                }
                if (selectedCouponIssues.isEmpty() || !selectedCouponIssues.get(0).getCouponIssueStatus().equals("1")) {
                    iterator.remove();
                    continue;
                }
                if (cugc != null && cugc.getIssueGiveCount() + 1 >= selectedCouponIssues.get(0).getGiveLimit()) {
                    iterator.remove();
                    continue;
                } else if (1 >= selectedCouponIssues.get(0).getGiveLimit()) {
                    iterator.remove();
                    continue;
                }
                couponIssueAll.addAll(selectedCouponIssues);
                List<CouponTemplate> couponTemplateList = selectedCouponIssues.get(0).getCouponTemplateList();
                List<Station> stationList = selectedCouponIssues.get(0).getStaList();
                for(CouponTemplate couponTemplate:couponTemplateList){
                    if (stationList != null && !stationList.isEmpty()) {
                        List<String> stationNames = stationList
                                .stream()
                                .map(Station::getStationName)
                                .filter(Objects::nonNull) // 过滤掉空值
                                .collect(Collectors.toList());
                        if (!stationNames.isEmpty()) {
                            String concatenatedNames = String.join(";", stationNames);
                            couponTemplate.setCouponStaNames(concatenatedNames);
                        }
                    }
                    couponTemplate.setCouDrawStatus("1");
                }
                couponInfoList.addAll(couponTemplateList);
            }
            if (couponIssueAll.size() > 0) {
                ExecutorService executorService = Executors.newFixedThreadPool(20); // 创建一个线程池，最多同时执行20个线程
                //该领取方式下可领取等级
                resultData = ResultData.success(couponInfoList);
                for (CouponIssue couponIssueItem : couponIssueAll) {

                    Runnable task = new Runnable() {
                        @Override
                        public void run() {
                            drawCoupon.setCouponIssueId(couponIssueItem.getCouponIssueId());
                            List<CouponTemplate> drawTemList = new ArrayList<>();
                            List<CouponUser> saveCouUserList = new ArrayList<>();           //用户领取的优惠券；
                            //用户能领取的优惠券
                            List<Integer> updateTemIdsCountMap = new ArrayList<>();
                            drawCoupon.setCouTemIds(couponIssueItem.getCouponTemplateList().get(0).getCouponTemplateId().toString());
                            // 生成后三位的字符串，保证至少有三位，不足的在前面补0
                            String counterString = couponIssueItem.getCouponIssueId().substring(0, 3);

                            // 获取原始的 randomFlag，即去掉后三位的部分
                            String originalRandomFlag = drawCoupon.getRandomFlag().substring(0, drawCoupon.getRandomFlag().length() - 3);

                            // 构建新的 randomFlag，将原始部分与后三位替换为循环数
                            String newRandomFlag = originalRandomFlag + counterString;

                            // 更新 drawCoupon 的 randomFlag
                            drawCoupon.setRandomFlag(newRandomFlag);
                            //优惠券模板，优惠券领取方式；
                            Map<String, Object> ciParam = new HashMap<>();
                            ciParam.put("couponIssueId", couponIssueItem.getCouponIssueId());
                            List<CouponIssue> couponIssues = couponService.selectCouponListByCouponIssueId(ciParam);

                            if (null != couponIssues && !couponIssues.isEmpty()) {
                                CouponIssue couponIssue = couponIssues.get(0);  //该领取方式与该优惠券的模板

                                List<CouponTemplate> couponTemplateList = couponIssues.get(0).getCouponTemplateList();

                                for (CouponTemplate couponTemplate : couponTemplateList) {                                    Date startTime = new Date();     //开始时间
                                    Date endTime = new Date();       //结束时间
                                    switch (couponTemplate.getEffectiveTimeType()) {
                                        case "1":   //固定时间
                                            //startTime = couponTemplate.getEffectiveTimeStart();
                                            endTime = couponTemplate.getEffectiveTimeEnd();
                                            break;
                                        case "2":   //领取后有效天数
                                            startTime = new Date();
                                            Calendar instance = Calendar.getInstance();
                                            instance.setTime(new Date());
                                            instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                            endTime = instance.getTime();
                                            break;
                                    }
                                    Long ccsdId = drawCoupon.getCcsdId() != null ? drawCoupon.getCcsdId().longValue() : 0;
                                    String activityName = "-";
                                    if (couponIssueIdsMap.containsKey("activity_name") && couponIssueIdsMap.get("activity_name") != null) {
                                        activityName = couponIssueIdsMap.get("activity_name").toString();
                                    }
                                    saveCouUserList.add(CouponUser.builder()
                                            .couponActivityId(couponActivityId)
                                            .mobilePhone(drawCoupon.getMobilePhone())
                                            .couponIssueId(couponIssueItem.getCouponIssueId())
                                            .couponTemplateId(couponTemplate.getCouponTemplateId())
                                            .couponIsUsed("0")
                                            .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                            .enterpriseId(couponIssue.getEnterpriseId())
                                            .couponGetTime(startTime)
                                            .activityType(0)
                                            .ccsdId(ccsdId)
                                            .activityName(activityName)
                                            .randomFlag(drawCoupon.getRandomFlag())
                                            .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                            .build());
                                    updateTemIdsCountMap.add(couponTemplate.getCouponTemplateId());
                                        couponService.insertCouponUserGiveCount(CouponUserGiveCount.builder()
                                                .mobilePhone(drawCoupon.getMobilePhone())
                                                .couponIssueId(couponIssueItem.getCouponIssueId())
                                                .createTime(new Date())
                                                .issueGiveCount(1)
                                                .enterpriseId(couponIssueItem.getEnterpriseId())
                                                .randomFlag(drawCoupon.getRandomFlag())
                                                .build());

                                }

                                      if (null != saveCouUserList && saveCouUserList.size() > 0) {
                                    int i = couponService.saveBatchCouponUser(saveCouUserList);

                                    log.info("批量保存的用户优惠券数量：" + i);
                                    int y = couponService.updateBatchCouponTemplate(updateTemIdsCountMap);
                                    log.info("批量更新的优惠券模板减少的模板优惠券数量：" + y);
                                }
                            }
                        }
                    };
                    executorService.execute(task); // 提交任务给线程池执行
                }
                executorService.shutdown(); // 关闭线程池
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // 等待所有任务执行完毕
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } else {
                resultData = ResultData.error(CodeMsg.NO_ISSUE); //必传参数不能为空
            }
        } else {
            resultData = ResultData.error(CodeMsg.NO_COUPON); //必传参数不能为空
        }

        return gson.toJson(resultData);
    }

    /***
     * 查询用户的优惠券
     * @param mobilePhone
     * @param mobilePhone
     * @param couponIsUsed
     * @param pageNum
     * @param pageSize
     * @return3
     */
    @RequestMapping(value = "/selectUserCoupons", method = RequestMethod.GET)
    @ApiOperation(value = "获取客户所拥有的优惠券")
    public String selectUserCoupons(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId,
                                    @ApiParam(value = "用户手机号", required = true) @RequestParam String mobilePhone,
                                    @ApiParam(value = "优惠券状态couponIsUsed 3是核销列表", required = true) @RequestParam String couponIsUsed,
                                    @ApiParam(value = "优惠券类型1现金劵，2折扣券，3兑换券 4洗车券 100全部", required = false) @RequestParam(required = false) String couponType,
                                    @ApiParam(value = "优惠券核销时间", required = false) @RequestParam(required = false) String verificationTimeString,
                                    @ApiParam(value = "油站ID", required = false) @RequestParam(required = false) Integer stationId,
                                    @RequestParam int pageNum, @RequestParam int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(mobilePhone) && StringUtils.isNotBlank(couponIsUsed) && enterpriseId != null) {
            //查询用户优惠券列  couponIsUsed：0，未使用；1，已使用； 2，已过期
            PageHelper.startPage(pageNum, pageSize);
            List<CouponUser> allUserCoupons;
            if (couponIsUsed.equals("2")) {
                CouponUser couponUser = CouponUser.builder()
                        .mobilePhone(mobilePhone)
                        .enterpriseId(enterpriseId)
                        .couponIsUsed(couponIsUsed).build();
                if(couponType!=null){
                    couponUser.setCouponType(couponType);
                }
                if(stationId!=null){
                    couponUser.setStationId(stationId);
                }

                allUserCoupons = couponService.selectUsedCoupons(couponUser);
            }else if(couponIsUsed.equals("3")) {
//                3核销
                CouponUser couponUser = CouponUser.builder()
                        .mobilePhone(mobilePhone)
                        .enterpriseId(enterpriseId)
                        .couponIsUsed(couponIsUsed).build();
                if(couponType!=null){
                    couponUser.setCouponType(couponType);
                }
                if(verificationTimeString!=null){
                    couponUser.setVerificationTimeString(verificationTimeString);
                }
                if(stationId!=null){
                    couponUser.setStationId(stationId);
                }
                allUserCoupons = couponService.selectUserAllCoupons(couponUser);
            }
            else {
                CouponUser couponUser = CouponUser.builder()
                        .mobilePhone(mobilePhone)
                        .enterpriseId(enterpriseId)
                        .couponIsUsed(couponIsUsed).build();
                if(couponType!=null){
                    couponUser.setCouponType(couponType);
                }
                if(verificationTimeString!=null){
                    couponUser.setVerificationTimeString(verificationTimeString);
                }
                if(stationId!=null){
                    couponUser.setStationId(stationId);
                }
                allUserCoupons = couponService.selectUserAllCoupons(couponUser);
            }
            PageInfo pageInfo = new PageInfo(allUserCoupons);
            resultData = ResultData.success(pageInfo);
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "手机号 优惠券状态couponIsUsed 油企ID 不能为空");
        }
        return gson.toJson(resultData);
    }


    @RequestMapping(value = "/couponDestroyList", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    @ApiOperation(value = "核销", httpMethod = "POST", notes = "pos机扫码核销")
    public  ResultData<?> couponDestroyList(@Valid @RequestBody CouponPaymetDto cw){
        logger.info("couponDestroyList--接口参数:{}",cw);
        List<String> couponNoList =  cw.getCouponNoList();
        int i = 0 ;
        Date date = new Date();   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String couponVtime = sdf.format(date);
        int couponxj = 0;
        int couponzk = 0;
        int couponxc = 0;
        for(String couponNo :couponNoList){
            CouponPaymetDto couponPayDto = new CouponPaymetDto();
            couponPayDto.setOilPersonnelId(cw.getOilPersonnelId());
            couponPayDto.setStationId(cw.getStationId());
            couponPayDto.setCouponNo(couponNo);
            couponPayDto.setCouponVtime(date);
            couponPayDto.setVerificationType(1);
            i++;
            ResultData res =   couponService.couponDestroyList(couponPayDto);
            if(res.getRetCode() == 0){
              if(res.getData().toString().equals("1")){
                  couponxj++;
                }
                if(res.getData().toString().equals("2")){
                    couponzk++;
                }
                if(res.getData().toString().equals("4")){
                    couponxc++;
                }
            }else{
                return ResultData.error("请重新选择第"+ i + "张优惠券"+res.getMessage());
            }
        }
        List<Map<String,Object>> userCouponDestroy = new ArrayList<>();
        if (couponxj>0){
            Map<String,Object> couponxjMap =  new HashMap<>();
            couponxjMap.put("couponType","1");
            couponxjMap.put("num",couponxj);
            userCouponDestroy.add(couponxjMap);
        }
        if (couponzk>0){
            Map<String,Object> couponzkMap =  new HashMap<>();
            couponzkMap.put("couponType","2");
            couponzkMap.put("num",couponzk);
            userCouponDestroy.add(couponzkMap);
        }
        if (couponxc>0){
            Map<String,Object> couponxcMap =  new HashMap<>();
            couponxcMap.put("couponType","4");
            couponxcMap.put("num",couponxc);
            userCouponDestroy.add(couponxcMap);
        }

        Map<String,Object> couponDestroyMap =  new HashMap<>();
        couponDestroyMap.put("couponVtime",couponVtime);
        couponDestroyMap.put("userCouponDestroy",userCouponDestroy);
        return ResultData.success(couponDestroyMap);
    }

    /***
     * 核销人员登录
     * @param cvu
     * @return
     */
    @PostMapping("/verificationUserLogin")
    @ApiOperation(value = "核销人员登录")
    public String verificationUserLogin(@RequestBody CouponVerificationUser cvu) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(cvu.getUserName()) && StringUtils.isNotBlank(cvu.getPassword())) {
            SysUser sysUser = posMachineService.selectUserByUserName(cvu.getUserName());
            if (null != sysUser) {
                if ("1".equals(sysUser.getEnterpriseId())) {
                    if ("0".equals(sysUser.getStatus())) {
                        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                        //密码加密判断已加密密码是否与真实密码相同
                        boolean matches = bCryptPasswordEncoder.matches(cvu.getPassword(), sysUser.getPassword());
                        if (matches) {
                            resultData = ResultData.success(sysUser);
                        } else {
                            resultData = ResultData.error(CodeMsg.PASSWORD_ERROR);
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.ACCOUNT_DISABLE);
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.NOT_COUPON_VERIFICATION_USER);
                }
            } else {
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "账号密码不能为空");
        }
        return gson.toJson(resultData);
    }

    /**
     * 查询核销的优惠券
     *
     * @param cver
     * @return
     */
    @PostMapping("/selectVerCouponInfo")
    @ApiOperation(value = "查询核销的优惠券")
    public String selectVerCouponInfo(@RequestBody CouponVerification cver) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(cver.getCouponNo()) && StringUtils.isNotBlank(cver.getUserName()) && StringUtils.isNotBlank(cver.getPassword())) {
            SysUser sysUser = posMachineService.selectUserByUserName(cver.getUserName());
            if (null != sysUser) {
                if ("1".equals(sysUser.getEnterpriseId())) {
                    if ("0".equals(sysUser.getStatus())) {
                        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                        //密码加密判断已加密密码是否与真实密码相同
                        boolean matches = bCryptPasswordEncoder.matches(cver.getPassword(), sysUser.getPassword());
                        if (matches) {
                            //获取该兑换券的核销站点
                            List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cver.getCouponNo()).build());
                            if (null != couponUsersInfo && couponUsersInfo.size() == 1) {
                                if (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {
                                    if ("0".equals(couponUsersInfo.get(0).getCouponIsUsed())) {
                                        CouponTemplate couponTemplateInfo = couponUsersInfo.get(0).getCouponTemplateInfo();
                                        if ("1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                                            if (null != couponTemplateInfo && "3".equals(couponTemplateInfo.getCouponType())) {
                                                boolean boo = false;
                                                if (StringUtils.isNotBlank(couponTemplateInfo.getVerification())) {
                                                    List<String> stringList = Arrays.asList(couponTemplateInfo.getVerification().split(","));
                                                    if (stringList.contains(sysUser.getStationId()))
                                                        boo = true;
                                                }
                                                if (sysUser.getEnterpriseId().equals(couponUsersInfo.get(0).getEnterpriseId().toString()))
                                                    boo = true;
                                                if (boo) {
                                                    resultData = ResultData.success(couponUsersInfo.get(0));
                                                } else {
                                                    resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "该兑换券核销站点与核销人员不一致");
                                                }
                                            } else {
                                                resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "该券不是兑换券");
                                            }
                                        } else {
                                            resultData = ResultData.error(CodeMsg.COUPON_LOSE_EFFECTIVE);
                                        }
                                    } else {
                                        resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_USED);
                                    }
                                } else {
                                    resultData = ResultData.error(CodeMsg.ERROR_COUPON_DATE);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "无此核销券");
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.PASSWORD_ERROR);
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.ACCOUNT_DISABLE);
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.NOT_COUPON_VERIFICATION_USER);
                }
            } else {
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "账号 密码 优惠券核销码 不能为空");
        }
        return gson.toJson(resultData);
    }

    /***
     * 优惠券核销
     * @param cv
     * @return
     */
    @PostMapping("/writeOffCoupon")
    @Transactional
    @ApiOperation(value = "优惠券核销")
    public String writeOffCoupon(@RequestBody CouponVerification cv) throws ParseException {
        log.info("/writeOffCoupon-" + cv.toString());
        Gson gson = new Gson();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(cv.getCouponNo()) && StringUtils.isNotBlank(cv.getUserName()) && StringUtils.isNotBlank(cv.getPassword())) {
            SysUser sysUser = posMachineService.selectUserByUserName(cv.getUserName());
            if (null != sysUser) {
                if ("1".equals(sysUser.getEnterpriseId())) {
                    if ("0".equals(sysUser.getStatus())) {
                        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                        //密码加密判断已加密密码是否与真实密码相同
                        boolean matches = bCryptPasswordEncoder.matches(cv.getPassword(), sysUser.getPassword());
                        if (matches) {
                            //获取该兑换券的核销站点
                            List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cv.getCouponNo()).build());
                            if (null != couponUsersInfo && couponUsersInfo.size() == 1) {
                                if (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {
                                    if ("0".equals(couponUsersInfo.get(0).getCouponIsUsed())) {
                                        CouponTemplate couponTemplateInfo = couponUsersInfo.get(0).getCouponTemplateInfo();
                                        if (null != couponTemplateInfo && "3".equals(couponTemplateInfo.getCouponType())) {
                                            if ("1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                                                boolean boo = false;
                                                if (StringUtils.isNotBlank(couponTemplateInfo.getVerification())) {
                                                    if (Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId()))
                                                        boo = true;
                                                }
                                                if (sysUser.getEnterpriseId().equals(couponUsersInfo.get(0).getEnterpriseId().toString()))
                                                    boo = true;
                                                if (boo) {
                                                    //更新用户优惠券信息
                                                    int i = couponService.updateCouponUser(CouponUser.builder().couponNo(cv.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(cv.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                                                    //更新优惠券使用模板数量
                                                    couponService.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                                                    if (1 == i)
                                                        resultData = ResultData.success(CodeMsg.SUCCESS);
                                                } else {
                                                    resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "该兑换券站点与核销人员不一致");
                                                }
                                            } else {
                                                resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "该优惠券已无效");
                                            }
                                        } else {
                                            resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "该券不是兑换券");
                                        }
                                    } else {
                                        resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_USED);
                                    }
                                } else {
                                    resultData = ResultData.error(CodeMsg.ERROR_COUPON_DATE);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.COUPON_VERIFICATION_ERROR, "无此核销券");
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.PASSWORD_ERROR);
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.ACCOUNT_DISABLE);
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.NOT_COUPON_VERIFICATION_USER);
                }
            } else {
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "账号 密码 优惠券核销码 不能为空");
        }

        return gson.toJson(resultData);
    }


    /**
     * 查询用户已核销的优惠券列表
     *
     * @param userName
     * @return
     */
    @GetMapping("/selectVerUserCouponList")
    public String selectVerUserCouponList(@RequestParam String userName, @RequestParam int pageNum, @RequestParam int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(userName)) {
            PageHelper.startPage(pageNum, pageSize);
            List<CouponUser> couponUserList = couponService.selectVerUserCouponList(CouponUser.builder().verificationUserAccount(userName).build());
            resultData = ResultData.success(new PageInfo(couponUserList));
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "userName不能为空");
        }
        return gson.toJson(resultData);
    }


    /**
     * 测试
     *
     * @param mobilePhone
     * @param stationId
     * @param amt
     * @return
     */
    @GetMapping("/initiativeCoupon")
    public String initiativeCoupon(String mobilePhone, Integer stationId, String amt) {
        couponService.initiativeCoupon(AppUserInfo.builder().mobilePhone(mobilePhone).userId(11062).stationId(7).build(), stationId, new BigDecimal(amt),null);
        return new Gson().toJson(ResultData.success("测试"));
    }

    //    提供给充值后发券
    public String drawCouponsForRecharge(String mobilePhone, List<String> couponIssueIds, Integer ccsdId, Integer activityType, String couponActivity,String orderNo) {
        ResultData resultData = ResultData.error(CodeMsg.INSERT_FAIL);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setMobilePhone(mobilePhone);
        drawCoupon.setCcsdId(ccsdId);
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        log.info("; 手机号：" + mobilePhone + "; 优惠券IDs：" + couponIssueIds + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        if (StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
            if (activityType == 5) {
                resultData = sendCoupon(drawCoupon, couponIssueIds, activityType, couponActivity,orderNo,"customer_card_use_record");
            } else {
                resultData = sendCoupon(drawCoupon, couponIssueIds, activityType, "0",orderNo,"customer_card_use_record");
            }
        }
        return gson.toJson(resultData);
    }

    //    提供给积分兑换发券
    @Async
    public String drawCouponsForIntegral(String mobilePhone, List<String> couponIssueIds,Integer activityType) {
        ResultData resultData = ResultData.error(CodeMsg.INSERT_FAIL);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setMobilePhone(mobilePhone);
        drawCoupon.setCcsdId(null);
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        log.info("; 手机号：" + mobilePhone + "; 优惠券IDs：" + couponIssueIds + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        if (StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
            resultData = sendCoupon(drawCoupon, couponIssueIds, activityType, "0",null,null);
        }
        return gson.toJson(resultData);
    }

    //    提供给充超级会员发券
    @Async
    public String drawCouponsForSuper(String mobilePhone, List<String> couponIssueIds,String bizType,Long bizId,Integer activityType) {
        ResultData resultData = ResultData.error(CodeMsg.INSERT_FAIL);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setMobilePhone(mobilePhone);
        drawCoupon.setCcsdId(null);
        drawCoupon.setBizId(bizId);
        drawCoupon.setBizType(bizType);
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        log.info("; 手机号：" + mobilePhone + "; 优惠券IDs：" + couponIssueIds + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        if (StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
                resultData = sendCoupon(drawCoupon, couponIssueIds, activityType, "0",null,null);
        }
        return gson.toJson(resultData);
    }

    @Async
    public  void drawCouponsForSaleActivity(String mobilePhone, List<String> couponIssueIds,String bizType,Long bizId,Integer activityType,Integer purchaseNum){
        log.info("秒杀发劵开始,phone:[{}],orderId:[{}],purchaseNum:[{}],issueIds:[{}]",mobilePhone,bizId,purchaseNum,couponIssueIds);
        for (int i = 0; i < purchaseNum; i++) {
            this.drawCouponsForSuper(mobilePhone, couponIssueIds, bizType, bizId, activityType);
        }
    }


    //    提供给支付后发券  这里只有wx zfb dzk支付
    @PostMapping("/drawCouponsCopy")
    public String drawCouponsCopy(@RequestBody DrawCoupon drawCoupon) {
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        log.info("领取活动ID：" + drawCoupon.getCouponIssueId() + "; 手机号：" + drawCoupon.getMobilePhone() + "; 优惠券IDs：" + drawCoupon.getCouTemIds() + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        String couponActivityId  =  drawCoupon.getCouponIssueId();
        if (StringUtils.isNotBlank(drawCoupon.getCouponIssueId()) && StringUtils.isNotBlank(drawCoupon.getCouTemIds()) &&
                StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
            List<String> couponIssueIds = new ArrayList<>();
            if (StringUtils.isNotBlank(drawCoupon.getOrdNo())) {
                PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(drawCoupon.getOrdNo());
                if (null == payOrder || "0".equals(payOrder.getStatus())) {
                    return gson.toJson(ResultData.error(CodeMsg.NO_PAY_ORDER));
                } else {
                    log.info("展示位优惠券订单号：" + drawCoupon.getOrdNo() + "; 订单应收金额：" + payOrder.getReceivedAmt());
                    //查询该couponIssueId是否存在
                    Map<String, Object> activity = couponService.getActivityAllByActivityId(drawCoupon.getCouponIssueId());

                    if (activity.isEmpty()) {
                        return gson.toJson(ResultData.error(CodeMsg.NO_COUPON_ISSUE));
                    } else {

                        BigDecimal receivedAmt;

                        if (payOrder.getPayType().equals("dzk")) {
                            BigDecimal receivableAmt = payOrder.getReceivableAmt() != null ? BigDecimal.valueOf(payOrder.getReceivableAmt()) : BigDecimal.ZERO;
                            BigDecimal discountAmt = payOrder.getDiscountAmt() != null ? BigDecimal.valueOf(payOrder.getDiscountAmt()) : BigDecimal.ZERO;
                            BigDecimal discountCoupon = payOrder.getDiscountCoupon() != null ? BigDecimal.valueOf(payOrder.getDiscountCouponAmt()) : BigDecimal.ZERO;

                            if (discountAmt != null && discountCoupon != null) {
                                receivedAmt = receivableAmt.subtract(discountAmt).subtract(discountCoupon);
                            } else if (discountAmt != null) {
                                receivedAmt = receivableAmt.subtract(discountAmt);
                            } else if (discountCoupon != null) {
                                receivedAmt = receivableAmt.subtract(discountCoupon);
                            } else {
                                receivedAmt = receivableAmt;
                            }
                        } else {
                            receivedAmt = payOrder.getReceivedAmt() != null ? BigDecimal.valueOf(payOrder.getReceivedAmt()) : BigDecimal.ZERO;
                        }


                        if ((Integer) activity.get("distribution_type") == 0) {
                            BigDecimal activityThreshold = new BigDecimal(activity.get("activity_threshold").toString());


                            if (receivedAmt.compareTo(activityThreshold) >= 0) {
                                couponIssueIds = couponService.getIssueIdsByActivityId(drawCoupon.getCouponIssueId());
                            }
                        } else if ((Integer) activity.get("distribution_type") == 1) {
                            couponIssueIds = couponService.getIssueIdsByActivityIdAndAmt(drawCoupon.getCouponIssueId(), receivedAmt);
                        }
                    }

                }
            } else {
                couponIssueIds = couponService.getIssueIdsByActivityId(drawCoupon.getCouponIssueId());
            }
            //drawCoupon.getCouponIssueId() 这个是活动ID
            resultData = sendCoupon(drawCoupon, couponIssueIds, 1, drawCoupon.getCouponIssueId(),drawCoupon.getOrdNo(),"pay_order");
        } else {
            resultData = ResultData.error(CodeMsg.NO_COUPON); //必传参数不能为空
        }
        return gson.toJson(resultData);
    }

    public ResultData sendCoupon(DrawCoupon drawCoupon, List<String> couponIssueIds, Integer activityType, String couponActivityId,String orderNo,String businessName) {
        ResultData resultData = null;
        Map<String, Object> activity = couponService.getActivityAllByActivityId(couponActivityId);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        List<CouponIssue> couponIssueAll = new ArrayList<>();

        Iterator<String> iterator = couponIssueIds.iterator();
        while (iterator.hasNext()) {
            String issueId = iterator.next();
            Map<String, Object> params = new HashMap<>();
            params.put("couponIssueId", issueId);
            List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
            int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(issueId).build());
            if (!selectedCouponIssues.isEmpty() && userIssueGiveCount >= selectedCouponIssues.get(0).getGiveCount()) {
                iterator.remove();
            }
            if (selectedCouponIssues.isEmpty() || !selectedCouponIssues.get(0).getCouponIssueStatus().equals("1")) {
                iterator.remove();
            }
        }
        for (String issueId : couponIssueIds) {
            Map<String, Object> params = new HashMap<>();
            params.put("couponIssueId", issueId);

            List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
            couponIssueAll.addAll(selectedCouponIssues);
        }

        if (couponIssueAll.size() > 0) {
            int counter = 1; // 初始化计数器
            List<CouponTemplate> drawTemList = new ArrayList<>();
            for (CouponIssue couponIssueItem : couponIssueAll) {
                drawCoupon.setCouponIssueId(couponIssueItem.getCouponIssueId());

                drawCoupon.setCouTemIds(couponIssueItem.getCouponTemplateList().get(0).getCouponTemplateId().toString());
                // 生成后三位的字符串，保证至少有三位，不足的在前面补0
                String counterString = String.format("%03d", counter);

                // 获取原始的 randomFlag，即去掉后三位的部分
                String originalRandomFlag = drawCoupon.getRandomFlag().substring(0, drawCoupon.getRandomFlag().length() - 3);

                // 构建新的 randomFlag，将原始部分与后三位替换为循环数
                String newRandomFlag = originalRandomFlag + counterString;

                // 更新 drawCoupon 的 randomFlag
                drawCoupon.setRandomFlag(newRandomFlag);

                // 增加计数器
                counter++;
                //优惠券模板，优惠券领取方式；
                Map<String, Object> ciParam = new HashMap<>();
                ciParam.put("couponIssueId", couponIssueItem.getCouponIssueId());
                List<CouponIssue> couponIssues = couponService.selectCouponListByCouponIssueId(ciParam);
//            if(StringUtils.isNotBlank(drawCoupon.getOrdNo())){
//                couponIssues = couponIssues.stream().sorted(Comparator.comparing(CouponIssue::getThresholdAmt).reversed()).collect(Collectors.toList());
//            }
                if (null != couponIssues && !couponIssues.isEmpty()) {
                    CouponIssue couponIssue = couponIssues.get(0);  //该领取方式与该优惠券的模板
                    //结束时间在当前时间之后
                    if (couponIssue.getEndDate().after(new Date())) {
                        //开始时间在当前时间之前
                        if (couponIssue.getStartDate().before(new Date())) {
                            String couTemIds = drawCoupon.getCouTemIds();
                            String[] splitCouTemIds = couTemIds.split(","); //用户领取的优惠券
                            //用户一次领取的优惠券张数是否已超过该领取方式限定的一次领取张数
                            if (splitCouTemIds.length <= couponIssue.getGiveLimit()) {
                                //查询用户进入该领取方式的次数
                                int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).build());
                                CouponUser couponUser1 = couponService.selectUserIssueRedomMax(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).build());
                                // 修改  这个应该是大于 ，当等于条件时，是可以继续领取的
                                if (userIssueGiveCount > couponIssue.getGiveCount()) {
                                    return ResultData.error(CodeMsg.COUPON_GIVE_COUNT_MAX);
                                } else if (userIssueGiveCount == couponIssue.getGiveCount() && couponUser1 != null && !couponUser1.getRandomFlag().equals(drawCoupon.getRandomFlag())) {
                                    return ResultData.error(CodeMsg.COUPON_GIVE_COUNT_MAX);
                                } else {
                                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(drawCoupon.getMobilePhone()).stationId(couponIssue.getEnterpriseId()).build());
                                    //该领取方式下可领取等级
                                    if ("plus".equals(couponIssue.getMemberCondition())) {
                                        //超级会员
                                        AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder()
                                                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                .userId(Long.valueOf(appUserInfo.getUserId()))
                                                .build());
                                        if (null == appUserSuperDetail)
                                            return ResultData.error(CodeMsg.COUPON_ISSUE_SUPER_LEVEL);
                                    }
                                    if ("part".equals(couponIssue.getMemberCondition())) {
                                        //用户等级 表示那些等级普通会员可以领取
                                        List<Grade> gradeList = gradeService.selectUserGrade(Grade.builder()
                                                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                .gradeGrowValue(appUserInfo.getGrowUpValue())
                                                .deleteFlag("0")
                                                .build());
//                                  TODO 如果前端置灰还有这种情况再做修改20230613
                                        if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode())) {
                                            return ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL);
                                        }
                                        Map<String, Object> param = new HashMap<>();
                                        param.put("stationId", appUserInfo.getStationId());
                                        param.put("mobilePhone", drawCoupon.getMobilePhone());
                                        int i = payOrderService.selectUserOrderCount(param);
                                        if ("newUser".equals(couponIssue.getMemberTags())) {
                                            if (i > 0) return ResultData.error(CodeMsg.COUPON_NEW_USER);
                                        }
                                        if ("oldUser".equals(couponIssue.getMemberTags())) {
                                            if (i <= 0) return ResultData.error(CodeMsg.COUPON_OLD_USER);
                                        }
                                    }
                                    //1、查询用户当天的参与的次数
//                                CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).randomFlag(drawCoupon.getRandomFlag()).build());
//                                if(null !=cugc){
//                                    //2、是否开启防作弊,防的是一天的进入页面的参与次数
//                                    if("0".equals(couponIssue.getAntiCheating()) && cugc.getIssueGiveCount() >= couponIssue.getCountOfDay())
//                                        return gson.toJson(ResultData.error(CodeMsg.MORE_DRAW_TODAY));
//                                    if("1".equals(couponIssue.getAntiCheating()) && cugc.getIssueGiveCount() == 1)
//                                        return gson.toJson(ResultData.error(CodeMsg.ONCE_DRAW_TODAY));
//                                }
                                    int count = couponService.selectCouponUserGiveCountByToday(CouponUserGiveCount.builder()
                                            .mobilePhone(drawCoupon.getMobilePhone())
                                            .couponIssueId(drawCoupon.getCouponIssueId())
                                            .curTimeSta(Date.from(LocalDate.now().atStartOfDay(ZoneOffset.ofHours(8)).toInstant()))
                                            .curTimeEnd(Date.from(LocalDate.now().plusDays(1).atStartOfDay(ZoneOffset.ofHours(8)).toInstant()))
                                            .build());
                                    if ("0".equals(couponIssue.getAntiCheating()) && count >= couponIssue.getCountOfDay())
                                        return ResultData.error(CodeMsg.MORE_DRAW_TODAY);
//                                if("1".equals(couponIssue.getAntiCheating()) && count >= 1)
//                                    return gson.toJson(ResultData.error(CodeMsg.ONCE_DRAW_TODAY));
//                                if("0".equals(couponIssue.getAntiMonthCheating())){
//                                    //如果 antiMonthCheating == 0 表示每月有限领次数
//                                    //Integer countOfMonth = couponIssue.getCountOfMonth();
//
//
//                                }


                                    List<CouponUser> saveCouUserList = new ArrayList<>();           //用户领取的优惠券；
                                    //用户能领取的优惠券
                                    List<Integer> updateTemIdsCountMap = new ArrayList<>();          //要更新的优惠券领取数量

                                    //优惠券模板列表
                                    List<CouponTemplate> couponTemplateList = couponIssues.get(0).getCouponTemplateList();
                                    if (null != couponTemplateList && couponTemplateList.size() > 0) {
                                        //获取用户同一个随机数已领取的优惠券
                                        List<CouponTemplate> temListByCouponUser = couponService.selectCouponTemListByCouponUser(CouponUser.builder()
                                                .randomFlag(drawCoupon.getRandomFlag()).couponIssueId(drawCoupon.getCouponIssueId()).mobilePhone(drawCoupon.getMobilePhone()).build());
                                        List<String> idsList = Arrays.asList(splitCouTemIds);
                                        for (CouponTemplate couponTemplate : couponTemplateList) {
                                            if (idsList.contains(couponTemplate.getCouponTemplateId().toString())) {
                                                if (couponTemplate.getCouponNum() > 0) {
                                                    if (null != temListByCouponUser && temListByCouponUser.size() > 0) {
                                                        List<Integer> collect = temListByCouponUser.stream().map(CouponTemplate::getCouponTemplateId).collect(Collectors.toList());
                                                        //如果同一个随机数已领取过，则返回前端 1 表示当前此优惠券已领取过；
                                                        if (collect.contains(couponTemplate.getCouponTemplateId())) {
                                                            couponTemplate.setCouDrawStatus("1");
                                                        } else {
                                                            Date startTime = new Date();     //开始时间
                                                            Date endTime = new Date();       //结束时间
                                                            //优惠券时间类型
                                                            switch (couponTemplate.getEffectiveTimeType()) {
                                                                case "1":   //固定时间
                                                                    //startTime = couponTemplate.getEffectiveTimeStart();
                                                                    endTime = couponTemplate.getEffectiveTimeEnd();
                                                                    break;
                                                                case "2":   //领取后有效天数
                                                                    startTime = new Date();
                                                                    Calendar instance = Calendar.getInstance();
                                                                    instance.setTime(new Date());
                                                                    instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                    endTime = instance.getTime();
                                                                    break;
                                                            }
                                                            Long ccsdId = drawCoupon.getCcsdId() != null ? drawCoupon.getCcsdId().longValue() : 0;
                                                            String activityName = "-";
                                                            if (activity != null && activity.containsKey("activity_name") && activity.get("activity_name") != null) {
                                                                activityName = activity.get("activity_name").toString();
                                                            }
                                                            saveCouUserList.add(CouponUser.builder()
                                                                    .couponActivityId(couponActivityId)
                                                                    .mobilePhone(drawCoupon.getMobilePhone())
                                                                    .couponIssueId(drawCoupon.getCouponIssueId())
                                                                    .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                    .couponIsUsed("0")
                                                                    .activityType(activityType)
                                                                    .activityName(activityName)
                                                                    .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                    .enterpriseId(couponIssue.getEnterpriseId())
                                                                    .couponGetTime(startTime)
                                                                    .randomFlag(drawCoupon.getRandomFlag())
                                                                    .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                    .ccsdId(ccsdId)
                                                                    .bizId(drawCoupon.getBizId())
                                                                    .bizType(drawCoupon.getBizType())
                                                                    .build());
                                                            updateTemIdsCountMap.add(couponTemplate.getCouponTemplateId());
                                                            couponTemplate.setCouDrawStatus("1");
                                                        }
                                                    } else {
                                                        Date startTime = new Date();     //开始时间
                                                        Date endTime = new Date();       //结束时间
                                                        //优惠券时间类型
                                                        switch (couponTemplate.getEffectiveTimeType()) {
                                                            case "1":   //固定时间
                                                                //startTime = couponTemplate.getEffectiveTimeStart();
                                                                endTime = couponTemplate.getEffectiveTimeEnd();
                                                                break;
                                                            case "2":   //领取后有效天数
                                                                startTime = new Date();
                                                                Calendar instance = Calendar.getInstance();
                                                                instance.setTime(new Date());
                                                                instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                endTime = instance.getTime();
                                                                break;
                                                        }
                                                        Long ccsdId = drawCoupon.getCcsdId() != null ? drawCoupon.getCcsdId().longValue() : 0;
                                                        String activityName = "-";
                                                        if (activity != null && activity.containsKey("activity_name") && activity.get("activity_name") != null) {
                                                            activityName = activity.get("activity_name").toString();
                                                        }
                                                        saveCouUserList.add(CouponUser.builder()
                                                                .mobilePhone(drawCoupon.getMobilePhone())
                                                                .couponActivityId(couponActivityId)
                                                                .couponIssueId(drawCoupon.getCouponIssueId())
                                                                .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                .couponIsUsed("0")
                                                                .activityType(activityType)
                                                                .activityName(activityName)
                                                                .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                .enterpriseId(couponIssue.getEnterpriseId())
                                                                .couponGetTime(startTime)
                                                                .randomFlag(drawCoupon.getRandomFlag())
                                                                .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                .ccsdId(ccsdId)
                                                                .bizId(drawCoupon.getBizId())
                                                                .bizType(drawCoupon.getBizType())
                                                                .build());
                                                        updateTemIdsCountMap.add(couponTemplate.getCouponTemplateId());
                                                        couponTemplate.setCouDrawStatus("1");
                                                    }
                                                } else {
                                                    //代表此优惠券数量不足
                                                    couponTemplate.setCouDrawStatus("2");
                                                }
                                            } else {
                                                couponTemplate.setCouDrawStatus("0");
                                                //获取用户同一个随机数已领取的优惠券
                                                if (null != temListByCouponUser && temListByCouponUser.size() > 0) {
                                                    List<Integer> collect = temListByCouponUser.stream().map(CouponTemplate::getCouponTemplateId).collect(Collectors.toList());
                                                    //如果同一个随机数已领取过，则返回前端 1 表示当前此优惠券已领取过；
                                                    if (collect.contains(couponTemplate.getCouponTemplateId()))
                                                        couponTemplate.setCouDrawStatus("1");
                                                }
                                            }

                                            if (couponIssues != null && !couponIssues.isEmpty()) {
                                                CouponIssue firstCouponIssue = couponIssues.get(0);
                                                if (firstCouponIssue != null) {
                                                    List<Station> stationList = firstCouponIssue.getStaList();
                                                    if (stationList != null && !stationList.isEmpty()) {
                                                        List<String> stationNames = stationList
                                                                .stream()
                                                                .map(Station::getStationName)
                                                                .filter(Objects::nonNull) // 过滤掉空值
                                                                .collect(Collectors.toList());

                                                        if (!stationNames.isEmpty()) {
                                                            String concatenatedNames = String.join(";", stationNames);

                                                            firstCouponIssue.getCouponTemplateList().get(0).setCouponStaNames(concatenatedNames);
                                                        }
                                                    }
                                                }
                                            }


                                            drawTemList.add(couponTemplate);
                                        }
                                    }
                                    if (null != saveCouUserList && saveCouUserList.size() > 0) {
                                        CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).randomFlag(drawCoupon.getRandomFlag()).build());
                                        if (null != cugc) {
                                            if (cugc.getIssueGiveCount() >= couponIssue.getGiveLimit()) {
                                                return ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX_NUM);
                                            } else {
                                                //用户分次领取后还可以领取的张数
                                                int i1 = couponIssue.getGiveLimit() - cugc.getIssueGiveCount();
                                                if (splitCouTemIds.length > i1) {
                                                    return ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX_NUM, "您已领取 " + cugc.getIssueGiveCount() + "张，还可领取 " + i1 + "张");
                                                } else {
                                                    //批量保存优惠券
                                                    if (!saveCouUserList.isEmpty()) {
                                                        CouponUser firstCouponUser = saveCouUserList.get(0);
                                                        saveCouUserList.clear();
                                                        saveCouUserList.add(firstCouponUser);
                                                    }
                                                    int i = couponService.saveBatchCouponUser(saveCouUserList);
                                                    log.info("批量保存的用户优惠券数量：" + i);
                                                    int y = couponService.updateBatchCouponTemplate(updateTemIdsCountMap);
                                                    log.info("批量更新的优惠券模板减少的模板优惠券数量：" + y);
                                                    couponService.updateCouponUserGiveCount(CouponUserGiveCount.builder()
                                                            .randomFlag(drawCoupon.getRandomFlag())
                                                            .issueGiveCount(saveCouUserList.size() + cugc.getIssueGiveCount())
                                                            .mobilePhone(drawCoupon.getMobilePhone())
                                                            .couponIssueId(drawCoupon.getCouponIssueId())
                                                            .build());
                                                }
                                            }
                                        } else {
                                            //批量保存优惠券
                                            if (!saveCouUserList.isEmpty()) {
                                                CouponUser firstCouponUser = saveCouUserList.get(0);
                                                saveCouUserList.clear();
                                                saveCouUserList.add(firstCouponUser);
                                            }
                                            int i = couponService.saveBatchCouponUser(saveCouUserList);
                                            log.info("批量保存的用户优惠券数量：" + i);
                                            int y = couponService.updateBatchCouponTemplate(updateTemIdsCountMap);
                                            log.info("批量更新的优惠券模板减少的模板优惠券数量：" + y);
                                            couponService.insertCouponUserGiveCount(CouponUserGiveCount.builder()
                                                    .mobilePhone(drawCoupon.getMobilePhone())
                                                    .couponIssueId(drawCoupon.getCouponIssueId())
                                                    .createTime(new Date())
                                                    .issueGiveCount(saveCouUserList.size())
                                                    .enterpriseId(appUserInfo.getStationId())
                                                    .randomFlag(drawCoupon.getRandomFlag())
                                                    .build());
                                        }
                                        if ("plus".equals(couponIssue.getMemberCondition())) {
                                            //超级会员
                                            AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder()
                                                    .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                    .userId(Long.valueOf(appUserInfo.getUserId()))
                                                    .build());
                                            if (null == appUserSuperDetail)
                                                return ResultData.error(CodeMsg.COUPON_ISSUE_SUPER_LEVEL);
                                            if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                                Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                                if (null != enterprise) {
                                                    couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                                }
                                            }
                                        }
                                        if ("part".equals(couponIssue.getMemberCondition())) {
                                            //用户等级 表示那些等级普通会员可以领取
                                            List<Grade> gradeList = gradeService.selectUserGrade(Grade.builder()
                                                    .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                    .gradeGrowValue(appUserInfo.getGrowUpValue())
                                                    .deleteFlag("0")
                                                    .build());
                                            if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode())) {
                                                return ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL);
                                            }
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("stationId", appUserInfo.getStationId());
                                            param.put("mobilePhone", drawCoupon.getMobilePhone());
                                            int i = payOrderService.selectUserOrderCount(param);
                                            if ("newUser".equals(couponIssue.getMemberTags())) {
                                                if (i > 0)
                                                    return ResultData.error(CodeMsg.COUPON_NEW_USER);
                                            }
                                            if ("oldUser".equals(couponIssue.getMemberTags())) {
                                                if (i <= 0)
                                                    return ResultData.error(CodeMsg.COUPON_OLD_USER);
                                            }
                                            if ("all".equals(couponIssue.getMemberCondition())) {
                                                if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                                    Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                                    if (null != enterprise) {
                                                        couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                                    }
                                                }
                                            }
                                        }
                                        if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                            if (null != enterprise) {
                                                couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                            }
                                        }

                                        //发送优惠券关联订单
                                        if(StringUtils.isNotEmpty(orderNo)&&StringUtils.isNotEmpty(businessName)){
                                                List<PresentCouponUserRecord> savePresentCouponUserRecords = new ArrayList<>();   //要保存的用户优惠券
                                                for (CouponUser couponUser : saveCouUserList) {
                                                    savePresentCouponUserRecords.add(PresentCouponUserRecord.builder()
                                                            .couponUserId(couponUser.getCouponUserId().longValue())
                                                            .businessName(businessName)
                                                            .orderNo(orderNo)
                                                            .build());
                                                }
                                                presentCouponUserRecordMapper.insertBatch(savePresentCouponUserRecords);
                                        }

                                    }
                                    resultData = ResultData.success(drawTemList);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX);
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.NOT_GIVE_COUPON_TIME);    //当前时间小于该领取方式的开始时间，表示该领取方式还未开始；
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.MORE_COUPON_TIME_END); //当前时间大于该领取方式结束时间；表示该领取方式已关闭
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.NO_COUPON_ISSUE); //没有表示该领取方式所对应的优惠券没有
                }
            }
        } else {
            resultData = ResultData.error(CodeMsg.NO_ISSUE); //必传参数不能为空
        }
        return resultData;

    }

    @GetMapping("/getRegisterCoupon")
    @ApiOperation(value = "获取注册发券的优惠券", notes = "获取注册发券的优惠券")
    @ResponseBody
    public String getRegisterCoupon(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId,
                                    @ApiParam(value = "用户手机号", required = true) @RequestParam String mobilePhone) {
        return couponService.getRegisterCoupon(enterpriseId, mobilePhone);
    }

    public String sendCounponByCardUserRecord(String ordNo) {
        CustomerCardUseRecord recordQuery = new CustomerCardUseRecord();
        recordQuery.setOrderNo(ordNo);
        CustomerCardUseRecord cardRecordByOrderNo = electronicMembershipCardService.getCardRecordByOrderNo(recordQuery);
        return sendCounponByCardUserRecord(cardRecordByOrderNo);
    }

    public String sendCounponByCardUserRecord(CustomerCardUseRecord cardRecordByOrderNo){
        if(cardRecordByOrderNo != null){
            String payType = cardRecordByOrderNo.getPayType();
            if (StringUtils.equals(CardRecordType.MANUAL_ADD.getKey(),payType)) {
                payType = "xj";
            }
            if (StringUtils.equals(CardRecordType.POS_RECHARGE.getKey(), payType)) {
                payType = "wx";
            }
            CouponInfoSettingDetail couponInfoSettingDetail = couponService.getCouponInfoIdByCustomerCardUseRecord(cardRecordByOrderNo,payType);
            log.info("充值后发优惠卷：{}",couponInfoSettingDetail);
            if(couponInfoSettingDetail != null && !couponInfoSettingDetail.getCouponIds().isEmpty()){
                try{
                    return drawCouponsForRecharge(cardRecordByOrderNo.getMobilePhone(),couponInfoSettingDetail.getCouponIds(), Math.toIntExact(couponInfoSettingDetail.getCcsdId()),2,null,cardRecordByOrderNo.getOrderNo());
                }catch (Exception ex){
                    log.info("充值后发优惠卷失败：{}",couponInfoSettingDetail);
                    log.error(ex.getMessage(),ex);
                }
            }
        }
        return null;
    }

//    public void registrationRelease(AppUserInfo appUserInfo){
//        //获取油企是否开启注册自动发券
//        log.info("获取油企是否开启注册自动发券：油企id：{}",appUserInfo.getStationId());
//        String couponActivity = couponService.getCouponActivity(appUserInfo.getStationId());
//        if (StringUtils.isNotBlank(couponActivity)){
//            log.info("获取发券方式：活动id：{}",couponActivity);
//            List<String> issueIdsByActivityId = couponService.getIssueIdsByActivityId(couponActivity);
//            if (CollectionUtil.isNotEmpty(issueIdsByActivityId)){
//                //调用发券接口
//                log.info("注册发券参数：{}，{}",appUserInfo.getMobilePhone(),issueIdsByActivityId);
//                drawCouponsForRecharge(appUserInfo.getMobilePhone(),issueIdsByActivityId,null,5,couponActivity);
//            }
//        }else {
//            log.info("该油企没有注册发券活动");
//        }
//    }

    @RequestMapping(value = "/cancelCoupon", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "优惠券扫码核销", httpMethod = "POST", notes = "优惠券扫码核销")
    public ResultData<?> cancelCoupon(@Valid @RequestBody CancelCouponDto cancelCouponDto) {
        log.info("cancelCoupon--接口参数:{}", cancelCouponDto);
        return couponWriteOffRecordsService.cancelCoupon(cancelCouponDto);
    }

    @GetMapping("/getIfCancelCouponSuccess")
    @ResponseBody
    @ApiOperation(value = "获取扫码核销的优惠券信息", httpMethod = "GET", notes = "获取扫码核销的优惠券信息")
    public ResultData<CouponInfoVO> getIfCancelCouponSuccess(@ApiParam(value = "优惠券码", required = true) @RequestParam String couponNo) {
        log.info("cancelCoupon--接口参数:{}", couponNo);
        return couponWriteOffRecordsService.getIfCancelCouponSuccess(couponNo);
    }

    @GetMapping("/batchPushWxGzhCouponExpire")
    @ApiOperation(value = "优惠券失效公众号推送通知", httpMethod = "GET", notes = "优惠券失效公众号推送通知")
    public void batchPushWxGzhCouponExpire() {
        couponService.batchPushWxGzhCouponExpire();
    }
}
